package com.dixon.worddayday.service;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.dixon.worddayday.config.security.JwtTokenProvider;
import com.dixon.worddayday.dao.CustomerRepository;
import com.dixon.worddayday.model.Customer;
import com.dixon.worddayday.request.WeChatLoginReq;
import com.dixon.worddayday.response.BaseRes;
import com.dixon.worddayday.response.ResponseCode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
@Slf4j
@RequiredArgsConstructor
public class AuthService {
    private final CustomerRepository customerRepository;
    private final PasswordEncoder passwordEncoder;
    private final WxMaService wxMaService;
    private final JwtTokenProvider jwtTokenProvider;

    public BaseRes<String> login(WeChatLoginReq loginReq) throws Exception {
        String code = loginReq.getCode();

        WxMaJscode2SessionResult wxMaJscode2SessionResult = wxMaService.jsCode2SessionInfo(code);
        try {
            // 1. 查找或创建用户
            Customer customer = customerRepository.findByOpenid(wxMaJscode2SessionResult.getOpenid());
            if (customer == null) {
                // 创建新用户
                customer = new Customer();
                customer.setName(wxMaJscode2SessionResult.getOpenid()); // 使用openid作为用户名
                // 生成随机密码
                customer.setPassword(passwordEncoder.encode(wxMaJscode2SessionResult.getOpenid().substring(0, 6)));
                customer.setOpenid(wxMaJscode2SessionResult.getOpenid());
                customer.setUnionid(wxMaJscode2SessionResult.getUnionid());
                customer.setCreateTime(LocalDateTime.now());
                customer = customerRepository.save(customer);
            } else if (wxMaJscode2SessionResult.getUnionid() != null && !wxMaJscode2SessionResult.getUnionid().equals(customer.getUnionid())) {
                // 更新unionid
                customer.setUnionid(wxMaJscode2SessionResult.getUnionid());
                customer = customerRepository.save(customer);
            }

            // 3. 生成JWT token
            String token = jwtTokenProvider.generateToken(customer.getName());
            return new BaseRes<>(token);

        } catch (Exception e) {
            log.error("微信登录失败: {}", e.getMessage(), e);
            return BaseRes.<String>builder()
                    .code(ResponseCode.BUSINESS_EXCEPTION.getCode())
                    .desc("微信登录失败: " + e.getMessage())
                    .build();
        }
    }
}
